import React, { Component } from 'react';
import {
  Button,
  message,
  Col,
  Row,
  Spin,
  Checkbox,
  Input,
  Form,
  InputNumber,
  Switch,
  Popconfirm,
  Modal,
  Radio,
  Select
} from 'antd';
const { Option } = Select;
import { messages } from 'share/common';
import InvoiceNum from 'containers/setting/invoice-bag/invoice-number-expense';
import InvoiceCon from 'containers/setting/invoice-bag/invoice-company-select';
import 'styles/setting/invoice-bag/invoice-bag-detail.scss';
import { LanguageInput } from 'components/index';
import invoiceBagService from 'containers/setting/invoice-bag/invoice-bag.service';
import { connect } from 'react-redux';
import Condition from 'components/condition';
import menuRoute from 'routes/menuRoute';
import Chooser from 'components/chooser';

const { If } = Condition;
const CheckboxGroup = Checkbox.Group;

class InvoiceBagEdit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      status: [
        { label: messages('components.key214'/*审批中*/), value: 1002 },
        { label: messages('components.key216'/*已通过*/), value: 1003 },
        { label: messages('components.key217'/*审核通过*/), value: 1004 },
        { label: messages('components.key218'/*开票通过*/), value: 1007 },
        { label: messages('components.key222'/*付款中*/), value: 1008 },
        { label: messages('components.key221'/*已付款*/), value: 1005 }
      ],
      loading: true,
      invoiceBagData: {
        i18n: {},
        statuses: [1003],
        maxExpenseReportSize: 100,
        minExpenseReportSize: 1,
        showInstructionsFlag: false
      },
      separateInspection: {
        firstLimitHelp: '',
        expenseNumHelp: '',
        companyHelp: ''
      },
      savingInvoiceBag: false,
      selRadio: 1,
      disabled: false,
      undefinedRule: false,
      canRun: true,
      isAll: true, // 默认全部标签
      selectedLabels: [],// 选中的标签
      labels: [
        { name: messages('setting.key2095')/*全部标签*/, value: 1 },
        { name: messages('setting.key2096')/*部分标签*/, value: 2 }
      ],
      invoiceBagList: menuRoute.getRouteItem('invoice-bag', 'key'),
      associatedTypeOptions: [{
        key: 0,
        title: messages('setting.key1728')/*不启用*/,
        description: messages('setting.key2235')/*报销单页面不可关联发票袋，只可在发票袋页面关联报销单*/
      }, {
        key: 2,
        title: messages('setting.key2236')/*启用，强制关联发票袋*/,
        description: (
          <div>
            1. {messages('setting.key2237')/*报销单页面可关联发票袋，并且必须关联发票袋才可提交发票袋*/}
            <br/>
            2. {messages('setting.key2238')/*当发票袋设置只可关联1个报销单，且当报销单到达本页面设置的条件时，自动提交发票袋*/}
          </div>
        )
      }],
    };
  }

  componentDidMount() {
    const { tenantMode, invoiceBagOID, configType } = this.props;
    if (tenantMode && !invoiceBagOID) {
      this.setState({ loading: false });
      return;
    }
    if (!tenantMode && configType === 'TENANT') {
      this.setState({ disabled: true });
    }
    this.getInvoiceBagDetail(this.props);
  }

  /**
   * 获取发票袋的配置
   * */
  getInvoiceBagDetail = (props) => {
    const { invoiceBagOID, configType } = props;
    let { invoiceBagData, selRadio } = this.state;
    let params = { configType, id: invoiceBagOID };
    invoiceBagService.getInvoiceBagDetail(params)
      .then(res => {
        const dataSources = invoiceBagOID ? res.data : res.data[0];
        if (dataSources) {
          const {
            i18n, id, companyOid, maxLength, preFix, minExpenseReportSize,
            maxExpenseReportSize, expenseReportStatuses,
            showInstructionsFlag, title, content, companyOids, statuses, companies, labels, associatedType
          } = dataSources;
          const formParams = { maxLength, preFix, content, title, labels };
          const stateParams = {
            i18n,
            id,
            companyOid,
            maxLength,
            preFix,
            minExpenseReportSize,
            maxExpenseReportSize,
            expenseReportStatuses,
            showInstructionsFlag,
            title,
            content,
            companyOids,
            statuses,
            companies,
            labels,
            associatedType
          };

          if (dataSources.companies && dataSources.companies[0]) {
            selRadio = 2;
          }
          if (labels && labels[0]) { // 是否选中标签，1表示全部，2表示部分
            formParams.labelsTag = 2;
          }
          !stateParams.i18n ? stateParams.i18n = {} : '';
          Object.assign(invoiceBagData, stateParams);
          this.setState({ invoiceBagData, selRadio }, () => {
            this.props.form.setFieldsValue(formParams);
          });
        } else {
          this.setState({ undefinedRule: true });
        }
      })
      .catch(err => {
        message.error(messages('common.error'));
      })
      .finally(() => {
        this.setState({
          loading: false
        });
      });
  };

  handleChangeLimit = (e) => {
    const tooLong = messages('setting.key1809')/*最多输入6个字符*/;
    const empty = messages('setting.key1810')/*请输入首位限制*/;
    const strValue = String(e.target.value);
    const { length } = strValue;
    const { separateInspection } = this.state;
    length > 6 ? separateInspection.firstLimitHelp = tooLong : (length < 1 ? separateInspection.firstLimitHelp = empty : separateInspection.firstLimitHelp = '');
    this.setState({ separateInspection });
    if (!separateInspection.firstLimitHelp) {
      let params = { preFix: e.target.value };
      invoiceBagService.checkPrefix(params)
        .then((response) => {
          if (!response.data.passFlag) {
            separateInspection.firstLimitHelp = response.data.message;
          }
        })
        .catch((err) => {
          message.error(err.response.data.message);
        })
        .finally((final) => {
          this.setState({ separateInspection });
        });
    }
  };

  handleChangeExpenseSize = (value) => {
    const minHelp = messages('setting.key1811')/*请输入关联报销单数量的最小值*/;
    const maxHelp = messages('setting.key1812')/*请输入关联报销单数量的最大值*/;
    const compareHelp = messages('setting.key1813')/*关联报销单数量的最大值必须小于等于最小值*/;
    const { minExpenseReportSize, maxExpenseReportSize } = value;
    const { separateInspection, invoiceBagData } = this.state;
    if (!minExpenseReportSize || !maxExpenseReportSize || minExpenseReportSize > maxExpenseReportSize) {
      !minExpenseReportSize ? separateInspection.expenseNumHelp = minHelp : (!maxExpenseReportSize ? separateInspection.expenseNumHelp = maxHelp : separateInspection.expenseNumHelp = compareHelp);
    } else {
      separateInspection.expenseNumHelp = '';
    }
    invoiceBagData.minExpenseReportSize = minExpenseReportSize;
    invoiceBagData.maxExpenseReportSize = maxExpenseReportSize;
    this.setState({ invoiceBagData, separateInspection });
  };

  handleChangeDescFlag = (showInstructionsFlag) => {
    let { invoiceBagData } = this.state;
    if (!showInstructionsFlag) {
      invoiceBagData.i18n = {};
      invoiceBagData.title = '';
      invoiceBagData.content = '';
      this.props.form.setFieldsValue({
        title: invoiceBagData.title,
        content: invoiceBagData.content
      });
    }
    invoiceBagData.showInstructionsFlag = showInstructionsFlag;
    this.setState(invoiceBagData);
  };

  handleChangeI18nTitle = (title, i18nTitle) => {
    const { invoiceBagData } = this.state;
    invoiceBagData.title = title;
    invoiceBagData.i18n.title = i18nTitle;
    this.setState({ invoiceBagData });
  };

  handleChangeI18nContent = (content, i18nContent) => {
    const { invoiceBagData } = this.state;
    invoiceBagData.content = content;
    invoiceBagData.i18n.content = i18nContent;
    this.setState({ invoiceBagData });
  };

  handleChangeCompany = (value) => {
    const { separateInspection, invoiceBagData } = this.state;
    const { selCompanies, selRadio } = value;
    if (selRadio === 2) {
      (selCompanies && selCompanies[0]) ? separateInspection.companyHelp = '' : separateInspection.companyHelp = messages('setting.key48')/*请选择公司*/;
    } else {
      separateInspection.companyHelp = '';
    }
    invoiceBagData.companies = selCompanies;
    this.setState({ invoiceBagData, separateInspection, selRadio });
  };

  handleChangeStatus = (checkedList) => {
    const { invoiceBagData } = this.state;
    invoiceBagData.statuses = checkedList;
    this.setState({
      invoiceBagData
    });
  };

  renderNoRules = () => {
    const { configType } = this.props;
    const copyWriting = messages('setting.key1814')/*未被分配租户级规则*/;
    const button = messages('setting.key786')/*新建规则*/;
    const newBagButton = (<Button type="primary" onClick={this.newInvoiceBag}>{button} </Button>);
    const newTenant = (<div style={{ color: '#cecece' }}>{copyWriting} </div>);
    if (configType === 'COMPANY') {
      return newBagButton;
    } else {
      return newTenant;
    }
  };

  newInvoiceBag = () => {
    this.setState({ undefinedRule: false });
  };

  handleClear = (e) => {
    e.preventDefault();
    this.handleDelete()
      .then(() => {
        let { invoiceBagData, undefinedRule } = this.state;
        const { tenantMode } = this.props;
        const params = {
          id: null,
          i18n: {},
          statuses: [1003],
          maxExpenseReportSize: 100,
          minExpenseReportSize: 1,
          showInstructionsFlag: false,
          companies: [],
          title: '',
          content: '',
          preFix: '',
          maxLength: '',
          associatedType: 0,
        };
        if (!tenantMode) undefinedRule = true;
        Object.assign(invoiceBagData, params);
        this.props.form.setFieldsValue({
          title: invoiceBagData.title,
          content: invoiceBagData.content,
          preFix: invoiceBagData.preFix,
          maxLength: invoiceBagData.maxLength
        });
        this.setState({ invoiceBagData, undefinedRule, selRadio: 1, loading: false });
      }, (() => {
        this.setState({ loading: false });
      }));
  };

  /**
   *
   * @returns {Promise<any>}
   * 删除发票袋
   */
  handleDelete = () => {
    const { invoiceBagData } = this.state;
    this.setState({ loading: true });
    return new Promise((resolve, reject) => {
      if (!invoiceBagData.id) {
        resolve(true);
      } else {
        invoiceBagService.deleteInvoiceBagConfig(invoiceBagData.id)
          .then(res => {
            message.success(messages('setting.key213')/*删除成功*/);
            resolve(true);
          })
          .catch(err => {
            reject(false);
            message.error(messages('common.error'));
          });
      }
    });
  };

  handleSave = (e) => {
    e.preventDefault();
    let { separateInspection, invoiceBagData } = this.state;
    const { tenantMode } = this.props;
    this.props.form.validateFieldsAndScroll((errors, values) => {
      if (!values.preFix) {
        separateInspection.firstLimitHelp = messages('setting.key1810')/*请输入首位限制*/;
        this.setState({ separateInspection });
      }
      if (!errors && !separateInspection.expenseNumHelp && !separateInspection.firstLimitHelp && !separateInspection.companyHelp) {
        if (tenantMode) {
          invoiceBagData.companyOids = invoiceBagData.companies && invoiceBagData.companies.map(item => item.companyOID);
        }
        const { title, content, preFix, maxLength, labels, associatedType } = values;
        invoiceBagData = { ...invoiceBagData, ...{ title, content, preFix, maxLength, labels, associatedType } };
        this.setState({ savingInvoiceBag: true });
        invoiceBagService.saveInvoiceBagConfig(invoiceBagData)
          .then(res => {
            if (res.data && res.data.code === '5006019') { //配置了拆单
              this.renderConfirmModal(e);
              return
            }
            invoiceBagData.id = res.data.id;
            this.setState({ invoiceBagData });
            message.success(messages('common.operate.success'));
            this.context.router.push(this.state.invoiceBagList.url);
          })
          .catch(err => {
            message.error(err.response.data.message);
          })
          .finally(final => {
            this.setState({ savingInvoiceBag: false });
          });
      }
    });
  };

  //渲染拆单确认框
  renderConfirmModal = (e) => {
    return (
      Modal.confirm({
        title: messages('setting.key2000')/*配置拆单则无法使用发票贷，是否去掉拆单？*/,
        content: (
          <div>
            <Row style={{color: '#f5222d'}}>{messages('setting.key2001')/*去掉拆单，报销单将不按照费用类型拆单。*/}</Row>
            <Row>{messages('setting.key2002')/*你还要继续吗？*/}</Row>
          </div>
        ),
        okText: messages('setting.key2003')/*继续*/,
        width: 450,
        iconType: 'exclamation-circle',
        onOk: () => this.handleCancelSplitProfile(e)
      })
    )
  };

  //取消拆单配置
  handleCancelSplitProfile = (e) => {
    this.setState({ savingInvoiceBag: true });
    invoiceBagService.cancelSplitProfile().then(() => {
      this.handleSave(e)
    }).catch(err => {
      this.setState({ savingInvoiceBag: false });
      message.error(err.response.data.message)
    })
  };

  renderFormFnc = () => {
    const { getFieldDecorator ,getFieldValue} = this.props.form;
    let { invoiceBagData, separateInspection, savingInvoiceBag, status, selRadio, disabled , labels, associatedTypeOptions } = this.state;
    const { tenantMode } = this.props;
    const titleLayOut = { span: 4, offset: 0 };
    const formInputLayout = { labelCol: { span: 4 }, wrapperCol: { span: 8 }, };
    const formCheckBoxItem = { labelCol: { span: 4 }, wrapperCol: { span: 20 }, };
    const titleInpRule = [{ length: 60, language: 'zh_cn' }, { length: 180, language: 'en' }];
    const contentInpRule = [{ length: 600, language: 'zh_cn' }, { length: 1800, language: 'en' }];
    const isShowLabels = getFieldValue('labelsTag') === 2;
    return (
      <div className="invoice-bag-detail">
        <Form onSubmit={this.handleSave}>
          <Row>
            <Col style={{ marginBottom: '32px' }} {...titleLayOut}
                 className='invoice-bag-detail-center invoice-bag-detail-title'>
              {messages('setting.key1815')/*编码规则设置*/}</Col>
          </Row>

          <Form.Item {...formInputLayout} label={messages('setting.key1816')/*位数限制*/}>
            {getFieldDecorator('maxLength', {
              rules: [{
                required: true,
                message: messages('common.can.not.be.empty', { name: messages('setting.key1816')/*位数限制*/ }),
              }]
            })(
              <InputNumber disabled={disabled} style={{ width: '100%' }} max={99} min={1}
                           step={1}
                           placeholder={messages('setting.key1817')/*请输入正整数，上限为99*/}/>
            )}
          </Form.Item>

          <Form.Item validateStatus={separateInspection.firstLimitHelp && 'error'}
                     help={separateInspection.firstLimitHelp}{...formInputLayout}
                     label={messages('setting.key1818')/*首位限制*/} required={true}>
            {getFieldDecorator('preFix')
            (<Input disabled={disabled} onChange={this.handleChangeLimit}
                    placeholder={messages('setting.key1809')/*最多输入6个字符*/}/>
            )}
          </Form.Item>

          <Row>
            <Col  {...titleLayOut} style={{ marginBottom: '32px' }}
                  className='invoice-bag-detail-center invoice-bag-detail-title'> {messages('setting.key1819')/*关联报销单设置*/}</Col>
          </Row>

          <Row>
            <Form.Item validateStatus={separateInspection.expenseNumHelp && 'error'}
                       help={separateInspection.expenseNumHelp}{...formCheckBoxItem}
                       label={messages('setting.key1820')/*报销单数量*/}>
              <InvoiceNum
                disabled={disabled}
                minExpenseReportSize={invoiceBagData.minExpenseReportSize}
                maxExpenseReportSize={invoiceBagData.maxExpenseReportSize}
                onChange={this.handleChangeExpenseSize}/>
            </Form.Item>
          </Row>

          <Form.Item{...formCheckBoxItem} label={messages('setting.key104')/*报销单状态*/}>
            <Row>
              <Col span={20} className='invoice-bag-detail-center'
                   style={{ 'justifyContent': 'left' }}>
                <CheckboxGroup
                  disabled={disabled}
                  options={status}
                  value={invoiceBagData.statuses}
                  onChange={this.handleChangeStatus}/>
              </Col>
            </Row>
          </Form.Item>

          <Form.Item{...formInputLayout} label={messages('setting.key2097')/*报销单标签包含*/}>
            {getFieldDecorator('labelsTag', {
              initialValue: 1
            })(
              <Radio.Group name="labels" onChange={this.handleRadioChange}>
                {labels.map(item => {
                  return <Radio  disabled={disabled} value={item.value}>{item.name}</Radio>;
                })}
              </Radio.Group>
            )}
          </Form.Item>

          <If value={isShowLabels}>
            <Form.Item wrapperCol={{ span: 8, offset: 4 }} >
              {getFieldDecorator('labels', {
                rules: [{
                  required: isShowLabels,
                  message: messages('setting.key2098')/*请选择报销单标签*/,
                }]
              })(
                <Chooser
                  placeholder={messages('common.please.select')}
                  type='select_expense_labels'
                  disabled={disabled}
                  labelKey='name'
                  valueKey='id'
                  showNumber={true}
                  single={false}/>
              )}
            </Form.Item>
          </If>

          <Form.Item {...formInputLayout} label={messages('setting.key2239')/*报销单关联发票袋*/}>
            {getFieldDecorator('associatedType', {
              initialValue: invoiceBagData.associatedType || 0
            })(
              <Select
                optionLabelProp="title"
                className="select-associated-type"
                disabled={disabled}
                getPopupContainer={() => document.getElementsByClassName('select-associated-type')[0]}
              >
                {associatedTypeOptions.map(item => (
                  <Option key={item.key} value={item.key} title={item.title}>
                    <div>{item.title}</div>
                    <div className="description">{item.description}</div>
                  </Option>
                ))}
              </Select>
            )}
          </Form.Item>

          <Form.Item>
            <Row>
              <Col  {...titleLayOut}
                    className='invoice-bag-detail-center invoice-bag-detail-title'> {messages('setting.key1758')/*说明文字*/}</Col>
              <Col span={18}>
                <Switch
                  disabled={disabled}
                  checked={invoiceBagData.showInstructionsFlag}
                  onChange={this.handleChangeDescFlag}/>
                <span style={{ marginLeft: '10px', fontSize: '12px' }}>
                  {messages('setting.key1821')/*启用后员工可在发票袋界面查看说明内容*/}</span>
              </Col>
            </Row>
          </Form.Item>

          {invoiceBagData.showInstructionsFlag &&
          <div>
            <Form.Item label={messages('setting.key1403')/*标题*/}{...formInputLayout} colon={true}>
              {getFieldDecorator('title', {
                rules: [{ message: messages('common.please.enter') },]
              })(<LanguageInput
                  disabled={disabled}
                  isEdit={invoiceBagData.id}
                  name={invoiceBagData.title}
                  inpRule={titleInpRule}
                  i18nName={invoiceBagData.i18n.title}
                  nameChange={this.handleChangeI18nTitle}
                  placeholder={messages('common.please.enter')}
                />
              )}
            </Form.Item>

            <Form.Item label={messages('setting.key1822')/*描述内容*/}{...formInputLayout} colon={true}>
              {getFieldDecorator('content', {
                rules: [{ message: messages('common.please.enter'), required: true },]
              })(<LanguageInput
                  disabled={disabled}
                  isEdit={invoiceBagData.id}
                  name={invoiceBagData.content}
                  i18nName={invoiceBagData.i18n.content}
                  nameChange={this.handleChangeI18nContent}
                  inpRule={contentInpRule}
                  textArea={true}
                  placeholder={messages('common.please.enter')}
                />
              )}
            </Form.Item>
          </div>
          }

          <If value={tenantMode}>
            <Row>
              <Col  {...titleLayOut}
                    className='invoice-bag-detail-center invoice-bag-detail-title'> {messages('setting.key730')/*适用公司*/}</Col>
              <Col span={8}>
                <Form.Item validateStatus={separateInspection.companyHelp && 'error'}
                           help={separateInspection.companyHelp}>
                  <InvoiceCon
                    disabled={disabled}
                    selCompanies={invoiceBagData.companies}
                    selRadio={selRadio}
                    onChange={this.handleChangeCompany}/>
                </Form.Item>
              </Col>
            </Row>
          </If>
          <Form.Item wrapperCol={{ span: 8, offset: 4 }} colon={true}>
            <Row>
              <If value={!tenantMode}>
                <Col span={6}>
                  <Popconfirm title={`${messages('setting.key272'/*确认删除？*/)}`}
                              placement="topRight"
                              okText={messages('common.ok')}
                              cancelText={messages('common.cancel')}
                              onConfirm={this.handleClear}>
                    <Button disabled={disabled}
                            type="default">
                      {messages('common.delete') /*删除*/}
                    </Button>
                  </Popconfirm>
                </Col>
              </If>
              <Col span={6}>
                <Button disabled={disabled} loading={savingInvoiceBag} type="primary"
                        htmlType="submit">
                  {messages('common.save') /*保存*/}
                </Button>
              </Col>
            </Row>
          </Form.Item>

        </Form>
      </div>
    );
  };

  render() {
    const { undefinedRule } = this.state;
    return (
      <Spin spinning={this.state.loading}
            delay={500}>
        {!undefinedRule ? this.renderFormFnc() : this.renderNoRules()}
      </Spin>
    );
  }
}

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode
  };
}

InvoiceBagEdit.propTypes = {
  invoiceBagOID: React.PropTypes.string,
  configType: React.PropTypes.string
};

InvoiceBagEdit.contextTypes = {
  router: React.PropTypes.object
};

const WrappedInvoiceBagCompany = Form.create()(InvoiceBagEdit);
export default connect(mapStateToProps)(WrappedInvoiceBagCompany);
